﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using SpLocalizer.Common;
using SpLocalizer.Common.DbApi;
using SpLocalizer.TranslationQueue;



namespace SpLocalizer.Application
{
    public partial class MainForm : Form
    {

        #region Properties

        private Guid SelectedProjectId
        {
            get
            {
                if (this.dataGridViewProjects.CurrentRow != null && !this.dataGridViewProjects.CurrentRow.Selected)
                {
                    return Guid.Empty;
                }
                int RowIndex = this.dataGridViewProjects.CurrentRow.Index;
                return ((List<Project>)this.dataGridViewProjects.DataSource)[RowIndex].ProjectId;
            }
        }


        /// <summary>
        /// Get the language translate from Value
        /// </summary>
        public string LngFrom
        {
            get
            {
                if (this.cmbLngFrom.SelectedValue != null)
                    return this.cmbLngFrom.SelectedValue.ToString();
                else
                    return String.Empty;
            }
        }


        /// <summary>
        /// Get the language translate to Value
        /// </summary>
        public string LngTo
        {
            get
            {
                if (this.cmbLngTo.SelectedValue != null)
                    return this.cmbLngTo.SelectedValue.ToString();
                else
                    return String.Empty;
            }
        }

        /// <summary>
        /// Get content source provider name
        /// </summary>
        public string ContentSourceProvider
        {
            get
            {
                if (this.cmbProviderName.SelectedItem != null)
                {
                    return this.cmbProviderName.SelectedItem.ToString();
                }
                else
                {
                    return String.Empty;
                }
            }
        }

        /// <summary>
        /// Return content source provider connection string 
        /// </summary>
        public string ProviderConnectionString
        {
            get
            {
                return this.txtUrl.Text;
            }
        }

        public bool IncludeDescendant{

            get
            {
                return this.chkIncludeDescendant.Checked;
            }
        }

        #endregion


       

        public MainForm()
        {
            InitializeComponent();
            BindToProjectsPersistentStore();
            btnImportEnable();
            BindComboboxes();
        }  
   
        private void BindToProjectsPersistentStore()
        {
            using (SpLocalizerEntities DbEntities = new SpLocalizerEntities())
            {
                this.dataGridViewProjects.AutoGenerateColumns = false;
                this.dataGridViewProjects.DataSource = DbEntities.Projects.OrderByDescending(p => p.ProjectDate).ToList<Project>();                
            }
        }

        private void BindComboboxes()
        {
          
          this.cmbLngFrom.DataSource = CultureInfo.GetCultures(CultureTypes.FrameworkCultures);
          this.cmbLngTo.DataSource = CultureInfo.GetCultures(CultureTypes.FrameworkCultures);
          this.cmbLngFrom.ValueMember = this.cmbLngFrom.DisplayMember = "Name";
          this.cmbLngTo.ValueMember = this.cmbLngTo.DisplayMember = "Name";
          this.cmbLngTo.SelectedItem = CultureInfo.CurrentCulture;
          this.cmbLngFrom.SelectedItem = CultureInfo.GetCultureInfo("en-US");            
        }


        #region Event Handlers

        private void btnImport_Click(object sender, EventArgs e)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                // Add Enterprise library dependency
                container.AddNewExtension<EnterpriseLibraryCoreExtension>();
                var section = (UnityConfigurationSection)ConfigurationManager.GetSection(Constants.UnityConfigSectionName);

                section.Configure(container);
                ServiceContainer.Container = container;

                var TranslationProject = container.Resolve<AbstractTranslationProject>(this.ContentSourceProvider);//"SpWebMetadataTranslationProject"
                CultureInfo FromLanguage = CultureInfo.GetCultureInfo(this.LngFrom);//"en-US"
                CultureInfo ToLanguage = CultureInfo.GetCultureInfo(this.LngTo); // ru-RU
                TranslationProject.CreateNewProject(this.ProviderConnectionString, this.IncludeDescendant);
                TranslationProject.ImportTranslationTasks(FromLanguage, ToLanguage);
            }
            BindToProjectsPersistentStore();
        }



        private void mnuItemTranslate_Click(object sender, EventArgs e)
        {
            using (IUnityContainer container = new UnityContainer())
            {

                // Add Enterprise library dependency
                container.AddNewExtension<EnterpriseLibraryCoreExtension>();
                var section = (UnityConfigurationSection)ConfigurationManager.GetSection(Constants.UnityConfigSectionName);

                section.Configure(container);
                ServiceContainer.Container = container;

                var pool = new TranslateThreadPool();
                pool.Start();               
            }
        }

        private void mnuItemExport_Click(object sender, EventArgs e)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                // Add Enterprise library dependency
                container.AddNewExtension<EnterpriseLibraryCoreExtension>();

                var section = (UnityConfigurationSection)ConfigurationManager.GetSection(Constants.UnityConfigSectionName);
                section.Configure(container);
                ServiceContainer.Container = container;

                var TranslationProject = AbstractTranslationProject.Open(SelectedProjectId);
                    TranslationProject.ExportTranslations();

            }
        }

        private void mnuItemDelete_Click(object sender, EventArgs e)
        {
            Guid ProjectIdToDelete = SelectedProjectId;
            //TODO: Check for Empty guid
            using (SpLocalizerEntities DbEntities = new SpLocalizerEntities())
            {
                Project ProjectToDelete = DbEntities.Projects.Where(p => p.ProjectId == ProjectIdToDelete).First<Project>();
                DbEntities.DeleteObject(ProjectToDelete);
                DbEntities.SaveChanges();
            }
            BindToProjectsPersistentStore();
        }
        #endregion

        #region UI management logic

        private void cmbProviderName_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnImportEnable();
        }


        private void cmbLngTo_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnImportEnable();
        }

        private void cmbLngFrom_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnImportEnable();
        }

        private void txtUrl_TextChanged(object sender, EventArgs e)
        {
            btnImportEnable();
        }

        private void btnImportEnable()
        {
            this.btnImport.Enabled = !String.IsNullOrEmpty(ProviderConnectionString) && !String.IsNullOrEmpty(this.LngTo) &&
                 !String.IsNullOrEmpty(this.LngFrom) && !String.IsNullOrEmpty(this.ContentSourceProvider);
        }

        #endregion
    }
}
